-- 准备地图 计分板
local GuildWarBattleScorePanel = app.mvc.createPanelClass(...)
local NewguildIconRender = require("app.newGuild.views.renders.NewguildIconRender")
local GuildWarRoundCountDown = import("..GuildWarRoundCountDown")

--data =
function GuildWarBattleScorePanel.createWithData(data, node)
    local sprite = GuildWarBattleScorePanel.extend(node or cc.CSLoader:createNode(Res.CSGuildWarBattleScorePanel))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end

function GuildWarBattleScorePanel.create(node)
    return GuildWarBattleScorePanel.createWithData(nil, node)
end

function GuildWarBattleScorePanel:init(data)
    self.super.init(self, data)
    self._guildIconRender1 = NewguildIconRender.create(self._ui["Panel/icon_1"])
    self._guildIconRender2 = NewguildIconRender.create(self._ui["Panel/icon_2"])
    self:registerViewEvent({
        {name = ViewEvent.CSGuildWar_MatchInfo, callback = handler(self, self._onGetMatchInfo)},
        {name = ViewEvent.CSGuildWar_EnterBattle, callback = handler(self, self._onEnterBattle)},
        {name = ViewEvent.CSGuildWar_LeaveBattle, callback = handler(self, self._onExitBattle)},
        {name = ViewEvent.CSGuildWar_BattleEmpty, callback = handler(self, self._onBattleEmpty)},
        {name = ViewEvent.CSGuildWar_HPChange, callback = handler(self, self._onHpChange)},
        
        
    })
    self._ui.Panel:setTouchEnabled(false)
    self._ui.btn_report:addClickEventListener(function()
        local matchInfo = UD.csGuildWarData:getCurMatchInfo()
        if matchInfo then
            app:sendMsg("CrossServerController", "popGuildWarFightReport", matchInfo:getId())
        end
    end)

    self._ui.btn_detail:addClickEventListener(function()
        UIHandler:handleMessage({id = Constant.FUNC_TYPE_CS_GUILD_WAR,mode = "open"})
    end)

    self._battleEmptyRound = nil
    self._curRound = nil

    self._isInFightingStage = false
    self._ui["Panel/tips"]:setString("")
    
    self._tips2 = self._ui["Panel/tips"]:clone()
    self._ui["Panel"]:addChild(self._tips2)
    self._tips2:setString("")

    self._tips3 = self._ui["Panel/tips"]:clone()
    self._ui["Panel"]:addChild(self._tips3)
    self._tips3:setString("")
    --开启定时器
    self:enableNodeEvents()

    self._isFirstGetData = true

    -- 请求数据
    UD.csGuildWarData:C2S_WorldGuildWarBattleField()
end

function GuildWarBattleScorePanel:onExit()
    self.super.onExit(self)
    self:_cleanCountDown()
    self:_stopRefreshScheduler()
end

function GuildWarBattleScorePanel:_cleanCountDown()
    if self._countDown then
        self._countDown:clean()
        self._countDown = nil
    end
end

function GuildWarBattleScorePanel:_onEnterBattle()
    self:setVisible(false)
    self._isInBattle = true
end

function GuildWarBattleScorePanel:_onExitBattle()
    self:setVisible(true)
    self._isInBattle = false
    UD.csGuildWarData:C2S_WorldGuildWarBattleField()
end

function GuildWarBattleScorePanel:_onBattleEmpty()
    self._battleEmptyRound = self._curRound

    if not self._emptyMessageBox then
        self._emptyMessageBox = display.newMessageBox(L("CSGuildWarBattleEmpty"),
        function()
            if cc.isAlive(self) then
                self._emptyMessageBox = nil
            end
        end)
        cc.Director:getInstance():getRunningScene():addChild(self._emptyMessageBox, 1000)
    end
end

-- 服务器 跟随组队的时候 会发送 hp = 0 消息 之后 hp 又恢复正常 --这里先延迟更新一下
function GuildWarBattleScorePanel:_onHpChange(eventName)
    if not self._delayUpdateHp then
        self._delayUpdateHp = true
        self:performWithDelay(function()
            self:_updateHpText()
           
            self._delayUpdateHp = nil
        end, 5)
    end
end

function GuildWarBattleScorePanel:_updateHpText()
    local stage = UD.csGuildWarData:getTodayStage()
    print("_updateHpText         ====>>",  UD.csGuildWarData:getHp(), UD.csGuildWarData:isMyGuildCanJoin() , stage == Enums.CSGuildWarTodayStage.Fighting )
    if UD.csGuildWarData:isMyGuildCanJoin() and stage == Enums.CSGuildWarTodayStage.Fighting then
        local isDie = UD.csGuildWarData:getHp() == 0
        if isDie then
            self._tips2:setString(L("playerHasNoLife"))
        else
            self._tips2:setString("")
        end
    end
end

function GuildWarBattleScorePanel:_popEndDialog()
    local isWin = UD.csGuildWarData:isMyGuildWin()
    if isWin == true then
        app:sendMsg("CrossServerController", "popGuildWarBattleWin")
    elseif isWin == false then
        app:sendMsg("CrossServerController", "popGuildWarBattleLose")
    else
        UD.csGuildWarData:C2S_LeaveWorldGuildWarMap()
    end
end



function GuildWarBattleScorePanel:_onFirstGetData()
    if UD.csGuildWarData:isMyGuildCanJoin() then
        self._countDown = GuildWarRoundCountDown.new({
            tickCallback = function(round, stage, nextBattTime, isStageChange)
                local str = ""
                if UD.csGuildWarData:isFightEnd() then
                    self:_cleanCountDown()
                    self:_stopRefreshScheduler()
                    self:setVisible(false)
                    self._ui["Panel/tips"]:setVisible(false)
                    self:_popEndDialog()
                    self._isInFightingStage = false
                else
                    local isBattleEmpty = false
                    if round == 0 then
                        if nextBattTime < 60 then
                            str = string.format(L("CSGuildWarBattleCountDown"), nextBattTime)
                        else
                            str = string.format(L("CSGuildWarBattleCountDown_1"), math.floor( nextBattTime/60 ), nextBattTime%60)
                        end
                        self._isInFightingStage = false
                    else
                        local isDie = UD.csGuildWarData:getHp() == 0
                        if stage == Enums.CSGuildWarRoundStage.FightStart and not isDie then
                            if self._battleEmptyRound and self._battleEmptyRound == round  then
                                -- 本轮战斗轮空状态
                                str = string.format(L("CSGuildWarRoundCountDown"), nextBattTime)
                                isBattleEmpty = true
                                self._battleEmptyRound = nil
                            else
                                str = L("CSGuildWarFindEnemy")
                            end
                        else
                            str = string.format(L("CSGuildWarRoundCountDown"), nextBattTime)
                        end

                        ----- 这里表示 一
                        self._isInFightingStage = true
                    end
                    self._curRound = round
                    self._ui["Panel/time"]:setString(str)

                    if isStageChange then
                        if stage == Enums.CSGuildWarRoundStage.Data then
                            if self._tips2:getString() == "" and self._tips3:getString() == "" then
                                self._ui["Panel/tips"]:setString(L("CSGuildWarBattleDataPrepare"))
                            end
                            EM:notify(ViewEvent.CSGuildWar_DeskTopStateChangge, 2)
                        elseif stage == Enums.CSGuildWarRoundStage.FightStart then
                            self._ui["Panel/tips"]:setString("")
                        elseif stage == Enums.CSGuildWarRoundStage.FightEnd then
                            EM:notify(ViewEvent.CSGuildWar_DeskTopStateChangge, 1)
                        elseif stage == Enums.CSGuildWarRoundStage.Prepare then
                            self._ui["Panel/tips"]:setString("")
                        end
                    end
                    -- 本轮轮空
                    if isBattleEmpty then
                        self._ui["Panel/tips"]:setString(L("CSGuildWarBattleEmpty"))
                        EM:notify(ViewEvent.CSGuildWar_DeskTopStateChangge, 1)
                    end
                    
                end
            end
        })
        self._countDown:startCountDown()
    end

    -- 当前 工会战 未开始 
    local stage = UD.csGuildWarData:getTodayStage()
    if not UD.csGuildWarData:isMyGuildCanJoin() or stage == Enums.CSGuildWarTodayStage.NotBegin or  stage == Enums.CSGuildWarTodayStage.End then
        UD.csGuildWarData:C2S_LeaveWorldGuildWarMap()
    end

    self:_updateHpText()
    if not self._refreshScoreSchedulerIdx then
        self._refreshScoreSchedulerIdx = scheduler.newCron(handler(self, self._refreshScoreTick), 5, true)
    end
end


function GuildWarBattleScorePanel:_onGetMatchInfo()
    if self._isFirstGetData then
        self._isFirstGetData = false
        self:_onFirstGetData()
    end
    self:refresh()
end

function GuildWarBattleScorePanel:refresh()
    local csGuildWarData = UD.csGuildWarData
    local matchInfo = csGuildWarData:getCurMatchInfo()
    if matchInfo then
        local guild1, guild2 = matchInfo:getGuildWithSort()
        -- 理论上 guild1 一定会有
        local wDay = app:getWeekDayPassDailyUpdate()
        if guild1 then
            self._guildIconRender1:setData(guild1:getGuildIconData())
            self._ui["Panel/Panel_data_1/server"]:setString(guild1:getServerName())
            self._ui["Panel/Panel_data_1/guild"]:setString(guild1:getGuildName())
            self._ui["Panel/Panel_data_1/num"]:setString(guild1:getMemberLifeNum())
            if wDay >= 6 then
                self._ui["Panel/Panel_data_1/ranking"]:setString(string.format(L("WGWPreGameRank"), guild1:getRank()))
            else
                self._ui["Panel/Panel_data_1/ranking"]:setString(string.format(L("WGWCurrentRank"), guild1:getRank()))
            end
        end

        if guild2 then
            self._guildIconRender2:setData(guild2:getGuildIconData())
            self._ui["Panel/Panel_data_2/server"]:setString(guild2:getServerName())
            self._ui["Panel/Panel_data_2/guild"]:setString(guild2:getGuildName())
            self._ui["Panel/Panel_data_2/num"]:setString(guild2:getMemberLifeNum())
            if wDay >= 6 then
                self._ui["Panel/Panel_data_2/ranking"]:setString(string.format(L("WGWPreGameRank"), guild2:getRank()))
            else
                self._ui["Panel/Panel_data_2/ranking"]:setString(string.format(L("WGWCurrentRank"), guild2:getRank()))
            end
        end
        -- 出现错误
        local errorStr = matchInfo:getError()
        if errorStr then
            self._tips3:setString(L("playerHasNoLife"))
        else
            self._tips3:setString("")
        end
    end
end

function GuildWarBattleScorePanel:_refreshScoreTick()
    if not self._isInBattle then
        if self._isInFightingStage then
            UD.csGuildWarData:C2S_WorldGuildWarBattleField()
        end
    end
end

function GuildWarBattleScorePanel:_stopRefreshScheduler()
    if self._refreshScoreSchedulerIdx then
        scheduler.cancelCron(self._refreshScoreSchedulerIdx)
        self._refreshScoreSchedulerIdx = nil
    end    
end




return GuildWarBattleScorePanel